const messageDao = require('../dao/messageDao');
const messageCfgDao = require('../dao/messageCfgDao');
const async = require('async');
const _ = require('lodash');
const errorTip = require('../util/errorTip');
const request = require("../util/request");
const util = require('../util/util');
const baseModel = require('./baseModel');
const push = require('../alicloud/push');
const SmsModel = require('./smsModel');

const MessageModel = Object.assign({

	dao: messageDao,

	del: function(req,callback){
		_.each(req.body,function(value,key){
			req.sanitizeBody(key).trim();
		});		

		req.checkBody({
			_id: {
				notEmpty: {
					errorMessage: errorTip['不可为空'].message
			    }
			}
		});

		req.getValidationResult().then(function(result) {
			
			if(result.isEmpty()){

				let {_id} = req.body;
				
				messageDao.remove({_id},callback)
			}
			else{
				let err = result.array({useFirstErrorOnly: true})[0];
				callback(err);
			}

		});
	},

	read: function(req, callback){
		_.each(req.body,function(value,key){
			req.sanitizeBody(key).trim();
		});		

		req.checkBody({
			_id: {
				notEmpty: {
					errorMessage: errorTip['不可为空'].message
			    }
			},
			read: {
				notEmpty: {
					errorMessage: errorTip['不可为空'].message
			    }
			}
		});

		req.getValidationResult().then(function(result) {
			
			if(result.isEmpty()){

				let {_id,read} = req.body;
				
				messageDao.save({_id,read},callback)
			}
			else{
				let err = result.array({useFirstErrorOnly: true})[0];
				callback(err);
			}

		});

	},

	sendAction: function (req,callback) {

		let body = req.body;
		let deviceType = body.deviceType;
		push
		.getPush()
		.push({
			AppKey:push.getAppKey(deviceType),
			//推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
			Target:"ACCOUNT", 
			//根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
			TargetValue:body.userId,
			PushType:"MESSAGE", //消息类型 MESSAGE NOTICE
			//设备类型 ANDROID iOS ALL.
			DeviceType:deviceType == "ANDROID" ? "ANDROID" :"iOS",
			Title:"INNER_ACTION",
			Body:body.action,
		},(err,result)=>{
			console.log(result);
		})

		callback(null);
	},

	send : function (req,callback) {

		let triggers = messageCfgDao.getTriggers();
		
		_.each(req.body,function(value,key){
			req.sanitizeBody(key).trim();
		});		

		req.checkBody({
			userId: {
				notEmpty: {
					errorMessage: errorTip['不可为空'].message
			    }
			},
			type: {
				notEmpty: {
					errorMessage: errorTip['不可为空'].message
			    }
			}
		});



		req.getValidationResult().then(result => {
			
			if(result.isEmpty()){

				let body = req.body;
				let {userId,deviceType} = body;
				let templdateData = body.data ? JSON.parse(body.data) : {};
				let user = {userId,deviceType};
				async.waterfall([
					(cb0)=>{
						if(deviceType){
							cb0(null,user);
						}else{
							request.get(req,'/user/getByUserId',{userId},function(err,response,ret){
								user = ret;
								cb0(err,ret);
							})
						}
					},
					(u,cb1)=>{
						messageCfgDao.query([
							{
								"$match":{
									messageType:'autoTrigger',
									trigger:body.type/* ,
									enable:true */
								}
							}
						],cb1)
					},
					(cfgList,cb2)=>{
						cfgList = cfgList || [];
						let messageList = [],noticeList = [],smsList = [];
						cfgList.forEach(v=>{
							let tmp = {
								userId,
								title:v.title,
								body:util.stringFormat(v.contentTemplate,templdateData),
								createTime:new Date,
								read:false,
								type:body.type
							};
							messageList.push(tmp);
							if(v.sendNotification){
								noticeList.push(tmp);
							}
							if(v.sendSms){
								smsList.push({
									type:body.type,
									data:body.data,
									phone:userId
								});
							}
						})

						if(noticeList.length){
							this.push("NOTICE",noticeList,user.deviceType);
						}
						if(smsList.length){
							this.sendSms(smsList);
						}
						this.push('MESSAGE',messageList,user.deviceType);
						messageDao.saveBatch(messageList,cb2)
					}
				],callback)
				
			}
			else{
				let err = result.array({useFirstErrorOnly: true})[0];
				callback(err);
			}

		});

	},

	push:function(pushType,pushList,deviceType){
		let funList = [];
		pushList.forEach(v=>{

			funList.push((cb)=>{
				
				let message = {
					AppKey:push.getAppKey(deviceType),
					//推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
					Target:"ACCOUNT", 
					//根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
					TargetValue:v.userId,
					PushType:pushType, //消息类型 MESSAGE NOTICE
					iOSApnsEnv:process.env.RUN_ENV == 'ONLINE' ? "PRODUCT" : "DEV",
					//设备类型 ANDROID iOS ALL.
					DeviceType:deviceType == 'ANDROID' ? deviceType : 'iOS',
					Title:v.title,
					Body:v.body
				}
				if(pushType == "MESSAGE"){
					message.Title = "INNER_MESSAGE";
					message.Body = JSON.stringify(v);
				}

				if(pushType == 'NOTICE'){
					message.AndroidOpenType="APPLICATION"
					message.AndroidPopupActivity="com.auctionmobile.PopupPushActivity";
					message.AndroidPopupTitle=message.Title
					message.AndroidPopupBody=message.Body
				}

				push.getPush()
				.push(message,cb)

			})

		});

		async.parallel(funList,(err,results)=>{
			if(err){
				console.error(err);
			}else{
				results.forEach(v=>{
					console.log(v);
				})
			}
		})
		
	},

	sendSms:function(pushList){
		pushList.forEach(v=>{
			SmsModel.send(v,function(err,ret){
				if(err){
					console.error(err);
				}else{
					console.log(ret);
				}
			})
		})
	},

	getMessageList: function(req,callback){

		let stages = [];
		let {userId} = req.query;
		if(userId){
			stages.push({
				"$match":{
					// userId
					userId:{
						"$in":[userId,'ALL']
					}
				}
			})
		}

		stages.push({
			"$sort":{createTime:-1}
		})

		this.getList(req, stages, (err, ret) => {
			callback(err, ret);
		});	

	},

	getUnreadCount: function(req, callback){
		
		let {userId} = req.query;

		if(!userId){
			callback({message:"缺少用户ID",code:1111});
			return;
		}

		messageDao.model.count({userId,read:false},(err,count)=>{
			callback(err,count);
		})
			
	}

}, baseModel);

module.exports = MessageModel;